package com.android.superobstacleavoider;

import java.io.IOException;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

import com.android.superobstacleavoider.framework.Music;

public class GameMusic implements Music, OnCompletionListener {
	private MediaPlayer m_mediaPlayer;
	private boolean m_isPrepared = false;

	public GameMusic(AssetFileDescriptor a_afd) {
		m_mediaPlayer = new MediaPlayer();
		m_isPrepared = false;
		try {
			m_mediaPlayer.setDataSource(a_afd.getFileDescriptor(),
					a_afd.getStartOffset(), a_afd.getLength());
			m_mediaPlayer.prepare();
			m_isPrepared = true;
			m_mediaPlayer.setOnCompletionListener(this);
		} catch (Exception e) {
			throw new RuntimeException("could not load music");
		}
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		synchronized (this) {
			m_isPrepared = false;
		}
	}

	@Override
	public void play() {
		if (m_mediaPlayer.isPlaying()) {
			return;
		}

		try {
			synchronized (this) {
				if (!m_isPrepared)
					m_mediaPlayer.prepare();
				m_mediaPlayer.start();
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void stop() {
		m_mediaPlayer.stop();
		synchronized (this) {
			m_isPrepared = false;
		}
	}

	@Override
	public void pause() {
		m_mediaPlayer.pause();
		synchronized (this) {
			m_isPrepared = false;
		}
	}

	@Override
	public void setLooping(boolean a_looping) {
		m_mediaPlayer.setLooping(a_looping);
	}

	@Override
	public void setVolume(float a_volume) {
		m_mediaPlayer.setVolume(a_volume, a_volume);
	}

	@Override
	public boolean isPlaying() {
		return m_mediaPlayer.isPlaying();
	}

	@Override
	public boolean isStopped() {
		return !m_isPrepared;
	}

	@Override
	public boolean isLooping() {
		return m_mediaPlayer.isLooping();
	}

	@Override
	public void dispose() {
		if (m_mediaPlayer.isPlaying())
			m_mediaPlayer.stop();
		m_mediaPlayer.release();
	}
}
